package com.village.zpark.controller;

import com.github.pagehelper.PageInfo;
import com.village.zpark.common.ResultMapUtil;
import com.village.zpark.pojo.Farmer;
import com.village.zpark.service.FarmerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("/farmer")
public class FarmerController {
    @Autowired
    private FarmerService farmerService;



    @RequestMapping
    public String Farmer(){
        return "/farmer";
    }

    @RequestMapping(value = "/farmerPage")
    public String FarmerPage(){
        return "/farmerPage";
    }

    @RequestMapping(value = "/farmerQueryById")
    public Object FarmerQueryById(@RequestParam(name = "id",required = true) Integer id, Model model){
        Farmer farmer = farmerService.findById(id);
        model.addAttribute("obj",farmer);
        return "/farmerPage";
    }

    @RequestMapping(value = "/farmerList")
    @ResponseBody
    public Object FarmerList(){
        List<Farmer> farmerList = farmerService.findAll();
        return ResultMapUtil.getHashMapList(farmerList);
    }


    @RequestMapping(value = "/addfarmer")
    @ResponseBody
    public Object addFarmer(Farmer farmer){
        try {
            int i = farmerService.addFarmer(farmer);
            return ResultMapUtil.getHashMapSave(i);
        } catch (Exception e) {
            return ResultMapUtil.getHashMapException(e);
        }
    }


    @RequestMapping(value = "/updatefarmer")
    @ResponseBody
    public Object updateFarmer(Farmer farmer){
        try {
            int i = farmerService.updateFarmer(farmer);
            return ResultMapUtil.getHashMapSave(i);
        } catch (Exception e) {
            return ResultMapUtil.getHashMapException(e);
        }
    }

    @RequestMapping(value = "/deletefarmer")
    @ResponseBody
    public Object deleteFarmer(Integer id){
        try {
            int i = farmerService.deleteFarmerById(id);
            return ResultMapUtil.getHashMapDel(i);
        } catch (Exception e) {
            return ResultMapUtil.getHashMapException(e);
        }
    }


    @RequestMapping(value = "/farmerQueryPage")
    @ResponseBody
    public Map<String, Object> farmerQueryPage(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer limit, String param) {
        PageInfo<Farmer> farmerPageInfo = farmerService.findPage(page, limit, param);
        Map<String,Object> map=new HashMap<>();
        map.put("code", 0);
        map.put("msg", "查询数据成功");
        map.put("count", farmerPageInfo.getTotal());
        map.put("data", farmerPageInfo.getList());
        return map;
    }
}
